package com.heima.article.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.config.CacheService;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.dtos.BehaviorDto;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import thread.BhThreadLocalUtil;
import thread.WmThreadLocalUtil;

import java.util.Date;

@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    private final CacheService cacheService;

    public ApCollectionServiceImpl(CacheService cacheService) {
        this.cacheService = cacheService;
    }


    /**
     * 收藏文章
     * @param collectionBehaviorDto
     * @return
     */
    @Override
    public ResponseResult collectionNews(CollectionBehaviorDto collectionBehaviorDto) {
        // 1.检查参数
        if (collectionBehaviorDto == null || collectionBehaviorDto.getEntryId() == null || collectionBehaviorDto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.创建ApCollection对象
        ApCollection apCollection = new ApCollection();
        // 获取当前用户对象id
        Integer userId = BhThreadLocalUtil.getUser().getId();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"当前为游客登录，不能收藏文章");
        }
        // redis的key
        String key = userId + "-" + collectionBehaviorDto.getEntryId();
        // 判断redis是否存在对应的key
        Boolean exists = cacheService.exists(key);
        BehaviorDto behaviorDto;
        if (exists){
            String redisKey = cacheService.get(key);
            behaviorDto = JSON.parseObject(redisKey,BehaviorDto.class);
        }else {
            behaviorDto = new BehaviorDto();
        }
        // 是否收藏判断
        if (collectionBehaviorDto.getOperation() == 0) {
            // 收藏
            BeanUtils.copyProperties(collectionBehaviorDto,apCollection);
            apCollection.setCollectionTime(new Date());
            save(apCollection);
            behaviorDto.setIscollection(true);
        } else if (collectionBehaviorDto.getOperation() == 1) {
            // 取消收藏
            removeById(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId,collectionBehaviorDto.getEntryId()));
            behaviorDto.setIsfollow(false);
        }
        // 将值重新存入当前key
        cacheService.set(key,JSON.toJSONString(behaviorDto));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
